<template>
    <div>
        <div class="operatBtnWrapper">
            <button class="operatBtn marR5" @click.stop="routerToAdd">新增组织架构</button>
            <button class="operatBtn marR5" v-if = "structureList.length > 0" @click.stop="routerToView">组织架构图</button>
		</div>

        <div class="marLR20">
            <el-table :data="formatData" :row-style="showRow"  class="tableWrapper"  border="true">
                <el-table-column v-for="(column, index) in columns" :key="column.value" :label="column.text" :width="column.width"  :align="column.text === '名称' ? 'left' : 'center'">
                    <template slot-scope="scope">
                        <template v-if="index === 0"><span v-for="space in scope.row._level" class="ms-tree-space" :key="space"></span></template>
                        <span class="tree-ctrl" v-if="iconShow(index,scope.row)" @click="toggleExpanded(scope.$index)">
                        <i v-if="!scope.row._expanded" class="el-icon-plus"></i>
                        <i v-else class="el-icon-minus"></i>
                        </span>
                        <template v-if = "column.type === '名称'">
                            {{scope.row[column.value] === null ? 0 : scope.row[column.value]}}
                        </template>
                        <template v-if = "column.type === '人员数量'">
                            {{scope.row[column.usersCount]}}
                        </template>
                        <span v-if = "column.type === '操作'">
                            <span title = "修改"  class="marR15" v-show = "scope.row.value !== 1">
                                <icon name="change" class="scaleIcon1" title="修改" @click.native.stop="routerToEditPage(scope.row)" style="cursor:pointer;"></icon>
                            </span>
                            <span title = "删除" v-show = "scope.row.children === undefined">
                                <icon name="del" class="scaleIcon1" title="删除" @click.native.stop="del(scope.row)" style="cursor:pointer;"></icon>
                            </span>
                        </span>
                    </template>
                    </el-table-column>
                    <slot></slot>
            </el-table>
        </div>
    </div>
</template>

<script>

import http from '@/assets/js/http'
import _g from '@/assets/js/global'
import treeToArray from '@/assets/js/eval'
 import { mapGetters } from 'vuex'

import treeTable from '@/components/Common/TreeTable'

    export default {
        components: { treeTable },  
        name: 'treeTable',
        data(){
            return{
                /* 表头 */
                // columns: [{
                //     text:'名称',
                //     value:'label',
                //     type:'名称',
                //     usersCount : 'users_count',//.未离职人员总数量
                // },{
                //     text:'操作',
                //     value:'',
                //     type:'操作',
                //     usersCount : 'users_count',//.未离职人员总数量
                // }],
                /* 表头 */
                columns: [{
                    text:'名称',
                    value:'label',
                    type:'名称',
                    usersCount : 'users_count',//.未离职人员总数量
                },{
                    text:'人员数量',
                    value:'label',
                    type:'人员数量',
                    usersCount : 'users_count',//.未离职人员总数量
                },{
                    text:'操作',
                    value:'',
                    type:'操作',
                    usersCount : 'users_count',//.未离职人员总数量
                }],
                structureList : [],//   所有组织架构列表
            }
        },
        created() {
            this.queryInfiniteLevelStructure()
        },
        computed: {
            // 格式化数据源
            formatData: function() {
                let tmp
                if (!Array.isArray(this.structureList)) {
                    tmp = [this.structureList]
                } else {
                     tmp = this.structureList
                }
                
                const func = treeToArray
                const args = Array.concat([tmp])

                return func.apply(null, args)
            }
        },
        methods: {
            /* 查询无限级组织架构 */
            queryInfiniteLevelStructure(){
                const that = this

                _g.showLoading('加载中');
                that.apiPost("admin/infiniteLevelStructure/queryInfiniteLevelStructure").then(res => {
                        _g.showLoading().close()
                        if(typeof res === 'string'){
                            res = JSON.parse(res)
                        }
                        if (res.code != 200) {
                            that.handleError(res)
                        } else if(res.data.isSuccess === 0){
                            that.structureList = res.data.result
                        }else if(res.data.isSuccess === 1){
                            _g.toastMsg("error", res.message)
                        }
                })
            },
             /* 跳转到新增组织架构页面 */
            routerToAdd(){
                this.$router.push('/admin/structures/addDepart')
            },
             /* 跳转到组织架构图页面 */
            routerToView(){
                this.$router.push('/admin/structures/viewStructure')
            },

            /* 前端递归删除对应记录 */
            IterationDelateMenuChildren(arr,value){
                const that = this
                if (arr.length) {
                    for (let i in arr) {
                        if (arr[i].children !==undefined && arr[i].children.length) {
                            that.IterationDelateMenuChildren(arr[i].children,value)
                        } else if(arr[i].value === value){
                            arr.splice(i,1)
                            break
                        }
                    }
                }
                return arr
            },

            /* 删除对应记录 */
            del(row){
                const that = this
                let structureList = that.structureList
                const len = structureList.length
                const structId = row.value

                that.$confirm('是否确认删除?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                        center: true
                    }).then(() => {
                            _g.showLoading('删除中')
                            that.apiPost('admin/infiniteLevelStructure/delete', {structId}).then((res) => {
                                _g.showLoading().close()
                                if(typeof res === 'string'){
                                    res = JSON.parse(res)
                                }
                                if (res.code != 200) {
                                    that.handleError(res)
                                } else {
                                    if(res.data.isSuccess === 0){
                                        _g.toastMsg("success", res.message)
                                        
                                         // 递归删除
                                        that.structureList = that.IterationDelateMenuChildren(structureList,structId)

                                    }else if(res.data.isSuccess === 1){
                                        _g.toastMsg("error", res.message)
                                    }else if(res.data.isSuccess === 2){
                                        _g.toastMsg("warning", res.message)
                                    }
                                }
                        })
                    }).catch(() => {})
            },

            /* 递归获取父类id */
            getParentId(oldParent,arr){
                let parentId = oldParent.parent_id
                if(oldParent.parent_id === 0){//   如果为顶层
                     arr.unshift(parentId)
                    return arr
                }else{
                    arr.unshift(parentId)
                    parentId = this.getParentId(oldParent.parent,arr)
                }
                return parentId
            },

            /* 跳转到编辑页面 */
            routerToEditPage(row){
                const name = row.label
                const structId = row.value

                let arr = []
                let structIdsStr = ''
                arr = this.getParentId(row,arr)
                structIdsStr = arr.join(',')
                this.$router.push({path : '/admin/structures/editDepart',query:{structIdsStr,name,structId}})
            },

            showRow: function(row) {
                const show = (row.row.parent ? (row.row.parent._expanded && row.row.parent._show) : true)
                row.row._show = show
                return show ? 'animation:treeTableShow 1s;-webkit-animation:treeTableShow 1s;' : 'display:none;'
            },
            // 切换下级是否展开
            toggleExpanded: function(trIndex) {
                const record = this.formatData[trIndex]
                record._expanded = !record._expanded
            },
            // 图标显示
            iconShow(index, record) {
                return (index === 0 && record.children && record.children.length > 0)
            }
        },
        mixins: [http]
    }
</script>
<style rel="stylesheet/css">
  @keyframes treeTableShow {
    from {opacity: 0;}
    to {opacity: 1;}
  }
  @-webkit-keyframes treeTableShow {
    from {opacity: 0;}
    to {opacity: 1;}
  }
</style>

<style lang="scss" rel="stylesheet/scss" scoped>
  $color-blue: #2196F3;
  $space-width: 18px;
  .ms-tree-space {
    position: relative;
    top: 1px;
    display: inline-block;
    font-style: normal;
    font-weight: 400;
    line-height: 1;
    width: $space-width;
    height: 14px;
    &::before {
      content: ""
    }
  }
  .processContainer{
    width: 100%;
    height: 100%;
  }
  table td {
    line-height: 26px;
  }

  .tree-ctrl{
    position: relative;
    cursor: pointer;
    color: $color-blue;
    margin-left: -$space-width;
  }
</style>